package com.example.librarymanagement.controller;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.librarymanagement.dto.role.RoleDto;
import com.example.librarymanagement.dto.role.RoleListDto;
import com.example.librarymanagement.entity.Role;
import com.example.librarymanagement.entity.RoleMenu;
import com.example.librarymanagement.entity.UserRole;
import com.example.librarymanagement.exception.BizException;
import com.example.librarymanagement.result.ResultCode;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author fgba
 * @since 2021-05-08
 */
@RestController
@RequestMapping("/sys/role")
public class RoleController extends BaseController {

    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('sys:role:list')")
    Role getRoleInfo(@PathVariable Integer id) {
        Role role = roleService.getById(id);
        List<RoleMenu> roleMenus = roleMenuService.list(new QueryWrapper<RoleMenu>().eq("role_id", id));
        List<Integer> menuIds = roleMenus.stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
        role.setMenuIds(menuIds);
        return role;
    }

    @GetMapping
    @PreAuthorize("hasAuthority('sys:role:list')")
    IPage<Role> getRoleList(RoleListDto roleListDto) {
        return roleService.page(
                new Page<>(roleListDto.getCurrent(), roleListDto.getSize()),
                new QueryWrapper<Role>().like(StrUtil.isNotBlank(
                        roleListDto.getName()), "name", roleListDto.getName())
        );
    }

    @PostMapping
    @PreAuthorize("hasAuthority('sys:role:save')")
    void addOrUpdRole(@Validated @RequestBody RoleDto roleDto) {
        if (!roleService.addOrUpdRole(roleDto)) {
            throw new BizException(ResultCode.HANDLE_FAIL);
        }
    }


    @DeleteMapping
    @Transactional(rollbackFor = {Exception.class})
    @PreAuthorize("hasAuthority('sys:role:delete')")
    void delRole(String ids) {
        List<Integer> idList = Arrays.asList(Convert.toIntArray(ids));
        roleService.removeByIds(idList);
        roleMenuService.remove(new QueryWrapper<RoleMenu>().in("role_id", idList));
        userRoleService.remove(new QueryWrapper<UserRole>().in("role_id", idList));
        for (Integer id : idList) {
            userService.clearUserAuthorityInfoByRoleId(id);
        }
    }

    @PostMapping("/perm/{id}")
    @Transactional(rollbackFor = {Exception.class})
    @PreAuthorize("hasAuthority('sys:role:perm')")
    List<Integer> permRole(@PathVariable(name = "id") Integer roleId, @RequestBody Integer[] menuIds) {
        List<RoleMenu> roleMenuList = new ArrayList<>();

        for (Integer menuId : menuIds) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuId);
            roleMenuList.add(roleMenu);
        }

        roleMenuService.remove(new QueryWrapper<RoleMenu>().eq("role_id", roleId));
        roleMenuService.saveBatch(roleMenuList);

        userService.clearUserAuthorityInfoByRoleId(roleId);
        return Arrays.asList(menuIds);
    }
}
